package com.example.chartroom.controller;

import com.example.chartroom.model.User;
import com.example.chartroom.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserMapper userMapper;

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest req){
        User user = userMapper.selectByname(username);
        if(user == null || !user.getPassword().equals(password)){
            System.out.println("登录失败! 用户名或密码错误" + user);
            return new User();
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        user.setPassword("");
        return user;
    }
    @PostMapping("/register")
    public Object register(String username,String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册 ret:" + ret);
            user.setPassword("");
        } catch (Exception e) {
            user = new User();
        }
        return user;

    }
    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest req){
        HttpSession session = req.getSession(false);
        if (session == null){
            System.out.println("[getUserInfo] 当前获取不到session对象");
            return new User();
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            System.out.println("[getUserInfo] 当前获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
